/* eslint-disable arrow-parens */
const Subscription = require('egg').Subscription;

class UpdateCache extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      interval: '2m', // 1 分钟间隔
      type: 'worker', // 指定所有的 worker 都需要执行
      immediate: true,
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    const res = await this.ctx.curl(
      'https://kyfw.12306.cn/otn/leftTicket/init',
      {
        dataType: 'text',
      }
    );
    console.log(res.headers['set-cookie']);
    const setcookies = res.headers['set-cookie'];
    const session = setcookies.find(
      (cookie) => cookie.indexOf('JSESSIONID') > -1
    );
    console.log('session', session);
    this.ctx.app.session = session;
  }
}

module.exports = UpdateCache;
